package server;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class ServerFrame extends JFrame implements Runnable {

	private JPanel top = new JPanel();
	private JPanel bottom = new JPanel();
	private JLabel text = new JLabel();
	private Thread thread = null;
	private boolean isRunning = false;
	
	public ServerFrame() {
		this.setLayout(new GridLayout(2,1));
		
		top.add(text);
		bottom.setLayout(new GridLayout(1,2));
		JButton start = new JButton("start");
		start.addActionListener(new StartActionListener());
		bottom.add(start);
		JButton exit = new JButton("stop");
		exit.addActionListener(new ExitActionListener());
		bottom.add(exit);
		this.add(top);
		this.add(bottom);
		
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		Integer portNumber;
		Integer broadCastPortNumber;
		
		portNumber = 3001;
		SmashTrisManager manager = new SmashTrisManager();
		
		broadCastPortNumber = portNumber + 1;
		// TODO Auto-generated method stub
		ServerSocket serverSocket = null;
		ServerSocket serverBroadcastSocket = null;
		try {
			serverSocket = new ServerSocket(portNumber);
			serverBroadcastSocket = new ServerSocket(broadCastPortNumber);
		} catch (IOException e) {
			System.out.println("Could not listen on port" + portNumber);
			System.exit(-1);
		}

		while (isRunning) {
			Socket clientSocket = null;
			Socket broadcastClientSocket = null;
			try {
				clientSocket = serverSocket.accept();
				broadcastClientSocket = serverBroadcastSocket.accept();
				System.out.println("Utworzono połączenie");
				// manager.addSocketToBroadCast(broadcastClientSocket);

				ObjectOutputStream out = new ObjectOutputStream(
						new BufferedOutputStream(
								broadcastClientSocket.getOutputStream()));
				out.flush();

				Connection connection = new Connection(clientSocket, out,
						manager);

			} catch (IOException e) {
				System.out.println("Accept failed: " + portNumber);
				System.exit(0);
			}
		}

	}
	
	
	private class StartActionListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			thread = new Thread(ServerFrame.this);
			isRunning = true;
			text.setText("running...");
			thread.start();
		}
		
	}
	
	private class ExitActionListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			System.exit(-1);
			text.setText("stop");
			isRunning = false;
			
		}
		
	}

}
